import json

from flask import Flask, request, jsonify
import pymysql
from read_mysql_homedata import save_mysql_lottery
from read_mysql_homedata import get_items_by_name
from read_mysql_homedata import get_items_by_id

from flask_cors import CORS

app = Flask(__name__)
CORS(app)


# 将数据插入到MySQL数据库
def insert_data(data):

    # 解析JSON数据并准备插入
    item_name = data['item_name']
    item_urllist = ','.join(data['item_urllist'])  # 假设picList是一个列表，需要转换为JSON字符串
    item_amount = data['item_amount']
    item_overtime = data['item_overtime'].split('Z')[0]
    item_status = 1
    item_categroy = data['item_categroy']
    item_use = data['item_use']
    item_position = data['item_position']
    postition_urllist = ','.join(data['postition_urllist'])  # 假设picList是一个列表，需要转换为JSON字符串
    remark = data['remark']

    # 假设你有一个名为`your_table`的表，其字段与你的JSON数据相对应
    sql = "INSERT INTO items (item_name, item_urllist, item_amount, item_overtime, item_status, item_categroy, item_use,item_position, position_urllist, remark) " \
          "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
    values = (item_name, item_urllist, item_amount, item_overtime, item_status, item_categroy, item_use,item_position, postition_urllist, remark)

    save_mysql_lottery(sql,values)


# 将数据插入到MySQL数据库
def update_data(data):

    # 解析JSON数据并准备插入
    id = data['id']
    item_name = data['item_name']
    item_urllist = ','.join(data['item_urllist'])  # 假设picList是一个列表，需要转换为JSON字符串
    item_amount = data['item_amount']
    item_overtime = data['item_overtime'].split('Z')[0]
    item_status = 1
    item_categroy = data['item_categroy']
    item_use = data['item_use']
    item_position = data['item_position']
    postition_urllist = ','.join(data['postition_urllist'])  # 假设picList是一个列表，需要转换为JSON字符串
    remark = data['remark']

    # 假设你有一个名为`your_table`的表，其字段与你的JSON数据相对应
    sql = "update items set item_name=%s, item_urllist=%s, item_amount=%s, item_overtime=%s, item_status=%s, item_categroy=%s, item_use=%s,item_position=%s, postition_urllist=%s, remark=%s " \
          "where id = %s"
    values = (item_name, item_urllist, item_amount, item_overtime, item_status, item_categroy, item_use,item_position, postition_urllist, remark,id)

    save_mysql_lottery(sql,values)



def query_data_by_name(name):
    return get_items_by_name(name)

def query_data_by_id(id):
    return get_items_by_id(id)

@app.route('/submit', methods=['POST'])
def save_data():
    # data1 = request.data
    # print("data:"+str(data1))
    # data2 = request.get_json()
    # print(data2)
    # data3 = request.form
    # print("form:"+str(data3))
    # 获取前端发送的JSON数据
    data = request.get_json()

    print(data)

    # form: ImmutableMultiDict(
    #     [('name', 'aaaaaa'), ('region1', '主卧'), ('region2', 'bbbbb'), ('date1', '2024-03-26T16:00:00.000Z'),
    #      ('delivery', 'false'), ('type[0]', '药品'), ('resource', '人吃的'), ('desc', 'cccccc'),
    #      ('url', 'http://180.76.60.31:8092/getimage/aaaaa.jpeg'), ('upfileList[0][name]', 'aaaaa.jpeg'),
    #      ('upfileList[0][url]', 'http://180.76.60.31:8092/getimage/aaaaa.jpeg'),
    #      ('upfileList[0][uid]', '1710512941084'), ('upfileList[0][status]', 'success'),
    #      ('picList[0]', 'http://180.76.60.31:8092/getimage/aaaaa.jpeg')])
    # print("get_json:"+ json.dumps(data))
    # 将数据插入到MySQL数据库
    if data is not None:
        insert_data(data)
    response = jsonify({'status': 'success','success':'true', 'message': 'Data saved successfully.'})
    # 设置CORS相关的响应头
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Methods', 'GET, POST')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
    # 返回成功响应
    return response, 200


@app.route('/getdata', methods=['POST'])
def get_data():

    data = request.get_json()

    # print(data)
    #
    # # 将数据插入到MySQL数据库
    if data is not None:
        result = query_data_by_name(data['item_name'])
        response = jsonify(result)
        # 设置CORS相关的响应头
        response.headers.add('Access-Control-Allow-Origin', '*')
        response.headers.add('Access-Control-Allow-Methods', 'GET, POST')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
        # 返回成功响应
        return response, 200
    return 400


@app.route('/updatedata', methods=['POST'])
def update_data():

    data = request.get_json()

    # print(data)
    #
    # # 将数据插入到MySQL数据库
    if data is not None:
        update_data(data)
        result = query_data_by_id(data['id'])
        response = jsonify(result)
        # 设置CORS相关的响应头
        response.headers.add('Access-Control-Allow-Origin', '*')
        response.headers.add('Access-Control-Allow-Methods', 'GET, POST')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
        # 返回成功响应
        return response, 200
    return 400



if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8093, debug=True)